<template>
  <div class="pb-20">
    <!-- 餐厅头部信息 -->
    <div class="relative">
      <img :src="restaurant.image" alt="" class="w-full h-48 object-cover">
      <div class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent fix items-end">
        <div class="p-4 text-white">
          <h2 class="text-xl font-bold">{{ restaurant.name }}</h2>
          <div class="flex items-center mt-1">
            <span class="text-yellow-300 text-sm mr-1"></span>
            <span class="text-gray-300 text-sm mr-2"></span>
            <span class="text-gray-300 text-sm"></span>
          </div>
          <div class="mt-2">
            <span class="inline-block bg-white/20 text-white text-xs px-2 py-1 rounded mr-2 mb-1">

            </span>
            <span class="inline-block bg-white/20 text-white text-xs px-2 py-1 rounded mr-2 mb-1">

            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品分类导航 -->
    <div class="bg-white sticky top-0 z-40 shadow-sm">
      <div class="fix overflow-x-auto">
        <div
            v-for="category in menuCategories"
            :key="category.id"
            class="px-4 py-3 whitespace-nowrap cursor-pointer"
            :class="{ 'text-primary-500 border-b-2 border-primary-500 font-medium': activeCategoryId === category.id }"
            @click="changeCategory(category.id)"
        >
          {{ category.name }}
        </div>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="bg-white">
      <div
          v-for="(category, index) in menuCategories"
          :key="category.id"
          v-show="activeCategoryId === category.id"
      >
        <div class="px-4 py-2 bg-gray-100 text-gray-600 text-sm">
          {{ category.name }}
        </div>
        <div class="divide-y">
          <div
              v-for="product in category.products"
              :key="product.id"
              class="p-4 fix gap-3"
          >
            <img :src="product.image" alt="" class="w-16 h-16 object-cover rounded">
            <div class="flex-1">
              <div class="fix justify-between">
                <h4 class="font-medium">{{ product.name }}</h4>
                <div class="fix items-center">
                  <span class="text-primary-500 font-medium">¥{{ product.price }}</span>
                </div>
              </div>
              <p class="text-gray-500 text-xs mt-1">{{ product.description }}</p>
              <div class="fix justify-between items-center mt-2">
                <div class="fix items-center">
                  <span class="text-gray-500 text-xs">月售{{ product.sales }}</span>
                </div>
                <div class="fix items-center">
                  <button
                      v-show="cartItems[product.id] > 0"
                      class="w-6 h-6 rounded-full bg-gray-100 fix items-center justify-center text-gray-700"
                      @click="decreaseQuantity(product.id)"
                  >
                    <i class="fa fa-minus text-xs"></i>
                  </button>
                  <span v-show="cartItems[product.id] > 0" class="mx-2 text-sm">{{ cartItems[product.id] }}</span>
                  <button
                      class="w-6 h-6 rounded-full bg-primary-500 fix items-center justify-center text-white"
                      @click="increaseQuantity(product.id, product.price, product.name)"
                  >
                    <i class="fa fa-plus text-xs"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车底部栏 -->
    <div class="fix bottom-16 left-0 right-0 bg-white shadow-[0_-2px_10px_rgba(0,0,0,0.1)]">
      <div class="flex items-center justify-between p-3">
        <div class="fix items-center">
          <div class="relative">
            <div class="w-12 h-12 rounded-full bg-gray-700 flex items-center justify-center text-white text-xl">
              <i class="fa fa-shopping-cart"></i>
            </div>
            <div
                v-if="totalQuantity > 0"
                class="absolute -top-1 -right-1 w-6 h-6 rounded-full bg-red-500 text-white text-xs fix items-center justify-center"
            >
              {{ totalQuantity }}
            </div>
          </div>
          <div class="ml-3">
            <div class="font-medium" :class="{ 'text-gray-400': totalPrice === 0 }">
              ¥{{ totalPrice.toFixed(2) }}
            </div>
            <div class="text-xs text-gray-500" v-if="totalPrice === 0">
              满¥{{ restaurant.minOrderAmount }}免配送费
            </div>
          </div>
        </div>
        <button
            class="px-6 py-2 bg-primary-500 text-white rounded-full font-medium"
            :disabled="totalPrice < restaurant.minOrderAmount"
            :class="{ 'bg-gray-300 cursor-not-allowed': totalPrice < restaurant.minOrderAmount }"
            @click="goToCheckout"
        >
          去结算
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 模拟餐厅数据
const restaurant = ref({
  id: 1,
  name: '',
  rating: 4.8,
  sales: 1234,
  distance: 1.2,
  deliveryTime: 30,
  minOrderAmount: 20,
  deliveryFee: 5
})

// 模拟菜单数据
const menuCategories = ref([
  {
    id: 1,
    name: '',
    products: [
      {
        id: 101,
        name: '香辣鸡腿堡',
        price: 18.0,
        description: '香辣鸡腿肉，搭配新鲜蔬菜和酱料',
        image: 'https://picsum.photos/100/100?random=21',
        sales: 567
      },
      {
        id: 102,
        name: '吮指原味鸡',
        price: 16.0,
        description: '鲜嫩多汁，外酥里嫩',
        image: 'https://picsum.photos/100/100?random=22',
        sales: 432
      },
      {
        id: 103,
        name: '老北京鸡肉卷',
        price: 15.0,
        description: '香嫩鸡肉搭配京葱和甜面酱',
        image: 'https://picsum.photos/100/100?random=23',
        sales: 345
      }
    ]
  },
  {
    id: 2,
    name: '小食',
    products: [
      {
        id: 201,
        name: '薯条(中)',
        price: 9.0,
        description: '金黄酥脆，口感细腻',
        image: 'https://picsum.photos/100/100?random=24',
        sales: 789
      },
      {
        id: 202,
        name: '吮指原味鸡',
        price: 10.0,
        description: '精选优质鸡肉，外酥里嫩',
        image: 'https://picsum.photos/100/100?random=25',
        sales: 654
      },
      {
        id: 203,
        name: '鸡米花',
        price: 12.0,
        description: '小块鸡肉，一口一个',
        image: 'https://picsum.photos/100/100?random=26',
        sales: 543
      }
    ]
  },
  {
    id: 3,
    name: '饮料',
    products: [
      {
        id: 301,
        name: '可口可乐(中)',
        price: 6.0,
        description: '碳酸饮料，清爽解渴',
        image: 'https://picsum.photos/100/100?random=27',
        sales: 987
      },
      {
        id: 302,
        name: '冰红茶',
        price: 6.0,
        description: '茶香浓郁，酸甜可口',
        image: 'https://picsum.photos/100/100?random=28',
        sales: 876
      },
      {
        id: 303,
        name: '咖啡',
        price: 10.0,
        description: '香浓咖啡，提神醒脑',
        image: 'https://picsum.photos/100/100?random=29',
        sales: 456
      }
    ]
  }
])

// 购物车状态
const cartItems = ref({})
const totalQuantity = computed(() => {
  return Object.values(cartItems.value).reduce((sum, quantity) => sum + quantity, 0)
})
const totalPrice = computed(() => {
  let total = 0
  for (const [productId, quantity] of Object.entries(cartItems.value)) {
    const product = findProductById(parseInt(productId))
    if (product) {
      total += product.price * quantity
    }
  }
  return total
})

// 查找商品
const findProductById = (productId) => {
  for (const category of menuCategories.value) {
    const product = category.products.find(p => p.id === productId)
    if (product) return product
  }
  return null
}

// 活跃分类
const activeCategoryId = ref(menuCategories.value[0].id)

// 生命周期钩子
onMounted(() => {
  // 根据路由参数获取餐厅ID，这里简单处理
  const restaurantId = parseInt(route.params.id)
  // 实际项目中应该根据ID获取餐厅详情
  console.log('加载餐厅ID:', restaurantId)

  // 从本地存储恢复购物车数据
  const savedCart = localStorage.getItem('cartItems')
  if (savedCart) {
    cartItems.value = JSON.parse(savedCart)
  }
})

// 监听购物车变化，保存到本地存储
watch(cartItems, (newValue) => {
  localStorage.setItem('cartItems', JSON.stringify(newValue))
}, { deep: true })

// 分类切换
const changeCategory = (categoryId) => {
  activeCategoryId.value = categoryId
}

// 购物车操作
const increaseQuantity = (productId, price, name) => {
  if (cartItems.value[productId]) {
    cartItems.value[productId]++
  } else {
    cartItems.value[productId] = 1
  }
}

const decreaseQuantity = (productId) => {
  if (cartItems.value[productId] > 1) {
    cartItems.value[productId]--
  } else {
    delete cartItems.value[productId]
  }
}

// 跳转到结算页面
const goToCheckout = () => {
  if (totalPrice.value >= restaurant.value.minOrderAmount) {
    router.push({ name: 'Checkout' })
  }
}
</script>